package com.hb.trade.api.im.hall.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.hb.core.pojo.enums.TradeWebsocketMsgEnum;
import com.hb.trade.api.im.main.TradeWebsocketSession;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.model.websocket.SocketMessageEntity;
import org.fzzn.core.websocket.config.OnlineCounter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 开标大厅时间定时任务
 *
 * @author Lix1ang
 * @date 2022-1-18 14:02:18
 */
@Slf4j
@Component
public class HallTimeTask {

    private static final JSONObject jsonObject = new JSONObject();

    private static final SocketMessageEntity messageEntity = SocketMessageEntity.getInstance();

    /**
     * 通过WebSocket消息发送当前系统时间    每秒执行一次
     */
    @Scheduled(cron = "* * * * * ?")
    public void task() {
        TradeWebsocketSession.clearAlreadyClose();
        //执行前先判断用户连接数量，如果还未连接则暂不执行
        int count = OnlineCounter.onlineCount();
        if (count == 0) {
            return;
        }
        //log.info("当前在线人数: {}", count);
        //TradeWebsocketSession.show();
        //构造WebSocket发送消息体
        jsonObject.putOpt("nowDay", DateUtil.today());
        jsonObject.putOpt("nowWeek", DateUtil.thisDayOfWeekEnum().toChinese());
        jsonObject.putOpt("nowHour", DateUtil.thisHour(true));
        jsonObject.putOpt("nowMinute", DateUtil.thisMinute());
        jsonObject.putOpt("nowSecond", DateUtil.thisSecond());
        messageEntity.setInfoType(TradeWebsocketMsgEnum.HALL_TIME_TASK.getCode());
        messageEntity.setTypeName(TradeWebsocketMsgEnum.HALL_TIME_TASK.getShowName());
        messageEntity.setContentData(jsonObject);
        //执行发送操作
        try {
            TradeWebsocketSession.sendSystemTimeToAll(messageEntity);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
